package com.hd.hdxgddcommon.utils.tree;


import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 树状结构工具类
 * </p>
 *
 * @author Administrator
 * @since 2018-10-30
 */
public class TreeSupport {
    /**
     * 把 Tree接口集合 转换为 树状结构数据
     *
     * @param list 实现Tree接口的集合
     * @param <T>
     * @return
     */
    public static <T extends Tree> List<T> listToTreeList(List<T> list) {
        Map<String, T> treeMap = list.stream()
                .collect(Collectors.toMap(Tree::getId, p -> p));
        LinkedList<T> newList = new LinkedList<>();
        list.forEach(tree -> {
            String parentId = tree.getParentId();
            if (parentId.equals(tree.getId())) {
                newList.add(tree);
            } else {
                T parent = treeMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(tree);
                } else {
                    newList.add(tree);
                }
            }

        });
        return newList;
    }
}
